package com.training.api.base;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.training.service.ProductService;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public abstract class BaseProductController extends HttpServlet {
    protected final ProductService productService;
    protected final ObjectMapper objectMapper;

    public BaseProductController() {
        this.productService = new ProductService();
        this.objectMapper = new ObjectMapper();
    }

    protected void handleError(HttpServletResponse response, Exception e) throws IOException {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Map<String, String> error = new HashMap<>();
        error.put("error", "Internal Server Error");
        error.put("message", e.getMessage());
        response.getWriter().write(objectMapper.writeValueAsString(error));
    }

    protected void sendJsonResponse(HttpServletResponse response, Object data) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(data));
    }

    protected int getIntParameter(String value, int defaultValue) {
        if (value != null && value.matches("\\d+")) {
            return Integer.parseInt(value);
        }
        return defaultValue;
    }

    protected String getIdFromPath(String pathInfo) {
        if (pathInfo != null && pathInfo.length() > 1) {
            // 移除开头的斜杠
            return pathInfo.substring(1);
        }
        return null;
    }
}
